package com.pig4cloud.pig.demo.Service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pig.demo.Mapper.Announcement2Mapper;
import com.pig4cloud.pig.demo.Mapper.AnnouncementMapper;
import com.pig4cloud.pig.demo.Mapper.UserMapper;
import com.pig4cloud.pig.demo.Service.AdviseService;
import com.pig4cloud.pig.demo.feign.Entity.Announcement;
import com.pig4cloud.pig.demo.feign.Entity.Announcement2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AdviseServiceImpl implements AdviseService {
    @Autowired
    private AnnouncementMapper announcementMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private Announcement2Mapper announcement2Mapper;


    @Autowired
    private KafkaTemplate template;
    private static final String topic="announcement";
    ObjectMapper om=new ObjectMapper();

    //消息生产者
    public void sendToKafka( String input,String title) throws Exception {
        System.out.println("我是sendtoKafka");
        Announcement announcment=new Announcement();
        announcment.setTitle(title);
        announcment.setNotice(input);
        announcment.setPublishTime(new Date());
        String s = om.writeValueAsString(announcment);
        System.out.println("发送之前");
        this.template.send(topic,s);
        System.out.println("发送之后");
    }

    //消息的消费者
    @KafkaListener(id="" ,topics=topic ,groupId = "groud.demo")
    public void listener(String  s) throws Exception {
        Announcement announcement = om.readValue(s, Announcement.class);

        System.out.println("=============接收到信息==========="+announcement);
        announcementMapper.insert(announcement);
        Announcement lastID = announcementMapper.findLastID();
        String aid = lastID.getAid();
        List<Long> list = userMapper.getIdList();
        for(long l:list){
            Announcement2 announcement2=new Announcement2();
            announcement2.setAid(aid);
            announcement2.setUid(l);
            announcement2.setIsdel(1);
            announcement2Mapper.insert(announcement2);
        }


    }
    //获取所有用户未删除的公告数据
    //将announcement中所有该用户没有删除公告查询出来,并将查询出来的数据置为已读
    //根据uid和delete
    public List<Announcement> findAnnoucement(String id){
        List<Announcement> a = announcementMapper.findA(id);
        return  a;
    }

    //删除单个公告
    public void delAnn(String aid,String uid){
        announcement2Mapper.delAnn(aid,uid);
    }

    //删除所有公告信息
    public void delAll(String uid){
        announcement2Mapper.delAll(uid);
    }
}
